﻿using System;
using Unis.Framework.Core.Exceptions;
using Unis.Framework.ORM.BaseDefiniens.Enums;
using Unis.Framework.ORM.Mapping;
using Unis.Framework.ORM.Xml;
using Unis.ORM.DbSql;

namespace Unis.Framework.ORM.DbSql
{
    public class BaseXmlSqlConfig : BaseSqlGenerator
    {
        // Methods
        public override SqlString[] GenerateDeleteSql(Type entityType)
        {
            return this.getSqlString(entityType, OperationType.Delete);
        }

        public override SqlString[] GenerateFindByKeySql(Type entityType, string[] properties)
        {
            return this.getSqlString(entityType, OperationType.SelectByKey);
        }

        public override SqlString[] GenerateInsertSql(Type entityType, string[] properties)
        {
            return this.getSqlString(entityType, OperationType.Insert);
        }

        public override SqlString[] GenerateSimpleSelectSql(Type entityType, string[] properties)
        {
            return this.getSqlString(entityType, OperationType.Select);
        }

        public override SqlString[] GenerateUpdateSql(Type entityType, string[] properties)
        {
            return this.getSqlString(entityType, OperationType.Update);
        }

        private string getSqlName(OperationType operationType)
        {
            switch (operationType)
            {
                case OperationType.Select:
                    return "SelectObject";

                case OperationType.SelectByKey:
                    return "SelectByKey";

                case OperationType.Insert:
                    return "AddObject";

                case OperationType.Update:
                    return "UpdateObject";

                case OperationType.Delete:
                    return "DeleteObject";

                case OperationType.DeleteNotIn:
                    return "DeleteNotInIDS";
            }
            throw new APPException("操作类型:" + operationType.ToString() + " 还没有配置相应SQL 操作名称！");
        }

        private SqlString[] getSqlString(Type entityType, OperationType operationType)
        {
            string xmlConfigFileName = AttMappingManager.Instance.GetModelMappingInfo(entityType).XmlConfigFileName;
            string sqlName = this.getSqlName(operationType);
            SqlString[] sqlString = SqlConfigHelper.Instance.GetSqlString(xmlConfigFileName, sqlName);
            CacheProxy.CacheSql(base.GenerateCacheKey(entityType, operationType), sqlString);
            return sqlString;
        }
    }
}
